/**
 * @description 更新购物车数量
 * @author unhejing (成都-敬宇杰)
 * @date 2020-02-23 上午10:44:54
 */
'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ' + event)

	// event.num = 1
	// event.id = "5e50d898be25c5004e11bf32";
	event.user_id = "1"
	if (event.user_id == '' || !event.user_id) {
		return {
			success: false,
			code: -1,
			msg: '参数错误，缺少用户id'
		}
	}
	if (event.num == '' || !event.num) {
		return {
			success: false,
			code: -1,
			msg: '参数错误，购物车num字段必传'
		}
	}
	if(!Number.isInteger(event.num)){
		return {
			success: false,
			code: -1,
			msg: '数量必须为整数'
		}
	}
	if(event.num <= 0){
		return {
			success: false,
			code: -1,
			msg: '数量必须大于等于0'
		}
	}
	if (event.id == '' || !event.id) {
		return {
			success: false,
			code: -1,
			msg: '参数错误，购物车id字段必传'
		}
	}

	// 根据购物车id更新数量
	let currentTime = new Date().getTime();
	let res = await db.collection('cart').doc(event.id).update({
		"num": event.num,
		"update_time": currentTime
	})
	
	console.log("************************华丽的分割线（以下为获取购物车列表）************************")
	// 获取所有购物车数据
	let allRes = await db.collection('cart').where({
		'user_id': event.user_id
	}).orderBy("create_time", "desc").get()
	if (allRes.data.length == 0) {
		return {
			success: false,
			code: -1,
			msg: '服务器内部错误'
		}
	}

	let cartList = allRes.data;
	let productIds = new Array();
	cartList.map(o => productIds.push(o.product_id))
	console.log("获取商品相关信息：" + JSON.stringify(productIds))
	// 获取商品相关信息
	const dbCmd = db.command;
	let productRes = await db.collection('product').where({
		_id: dbCmd.in(productIds)
	}).get()
	let productList = productRes.data;
	console.log("productList:" + JSON.stringify(productList))
	let productMap = new Map();
	productList.map(o => {
		productMap.set(o._id, o);
	})
	console.log("productMap:" + JSON.stringify(productMap.size))
	// 设置购物车信息
	cartList = await cartList.map(o => {
		let product = productMap.get(o.product_id);
		if (product) {
			o.product_code = product.product_code
			o.product_name = product.product_name
			o.sale_price = product.sale_price
			o.book_price = product.book_price
			o.primary_img = product.primary_img
			o.publish_status = product.publish_status
		}
		return o;
	})
	// 设置商品信息
	if (allRes.id || allRes.affectedDocs >= 1) {
		return {
			success: true,
			code: 0,
			msg: '添加成功',
			data: cartList
		}
	}
	return {
		success: false,
		code: -1,
		msg: '服务器内部错误'
	}
};
